﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Web;
using System.Web.SessionState;
using Rhino.Mocks;

namespace ActivateYourGlutes.Tests.Unit.Mocks
{
    public class MockHttpContext : HttpContextBase
    {
        public const string Url = "http://localhost/";

        private IPrincipal _user;
        private HttpSessionStateBase _sessionStateBase;
        private HttpRequestBase _requestBase;
        private HttpResponseBase _responseBase;

        public bool IsAjaxRequest { get; set; }

        public MockHttpContext()
        {
            IsAjaxRequest = false;
        }

        public MockHttpContext(HttpSessionStateBase sessionStateBase, HttpRequestBase requestBase)
        {
            _sessionStateBase = sessionStateBase;
            _requestBase = requestBase;
        }

        public override IPrincipal User
        {
            get
            {
                if (_user == null)
                {
                    _user = MockRepository.GenerateStub<IPrincipal>();
                    _user.Stub(u => u.Identity.Name).Return("testuser");
                    _user.Stub(u => u.Identity.IsAuthenticated).Return(true);
                }
                return _user;
            }
            set
            {
                _user = value;
            }
        }

        public override HttpSessionStateBase Session
        {
            get
            {
                if (_sessionStateBase == null)
                {
                    _sessionStateBase = MockRepository.GenerateStub<HttpSessionStateBase>();
                }
                return _sessionStateBase;
            }
        }

        public override HttpRequestBase Request
        {
            get
            {
                if (_requestBase == null)
                {
                    _requestBase = MockRepository.GenerateStub<HttpRequestBase>();
                    _requestBase.Stub(r => r.Url).Return(new Uri(Url));
                    if (IsAjaxRequest)
                        _requestBase.Stub(r => r.Headers["X-Requested-With"]).Return("XMLHttpRequest");
                }
                return _requestBase;
            }
        }

        public override HttpResponseBase Response
        {
            get
            {
                if (_responseBase == null)
                {
                    _responseBase = MockRepository.GenerateStub<HttpResponseBase>();
                }
                return _responseBase;
            }
        }
    }
}
